<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="编码类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="codeType">
              <j-dict-select-tag type="list" v-model="model.codeType" dictCode="mdm_code_type" placeholder="请选择编码类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="前缀" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="prefix">
              <a-input v-model="model.prefix" placeholder="请输入前缀"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="包含日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="dateFlag">
              <j-switch v-model="model.dateFlag" :options="[1,0]" ></j-switch>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="日期格式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="dateFmt">
              <j-dict-select-tag type="list" v-model="model.dateFmt" dictCode="mdm_date_fmt" placeholder="请选择日期格式" :disabled="String(model.dateFlag) === '0'"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="当前序列号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="seqNo">
              <a-input-number v-model="model.seqNo" placeholder="请输入当前序列号" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="序列号长度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="seqLen">
              <a-input-number v-model="model.seqLen" placeholder="请输入序列号长度" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="编码案例" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="codeExample">
              <a-input v-model="model.codeExample" placeholder="请输入编码案例" disabled ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="启用标志" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="enableFlag">
              <j-switch v-model="model.enableFlag" :options="[1,0]" ></j-switch>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'

  export default {
    name: 'MdmCodeRuleForm',
    components: {
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        model:{
            dateFlag:"1",
            dateFmt:"yyyyMM",
            seqNo:1,
            seqLen:5,
            enableFlag:"1",
         },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
           codeType: [
              { required: true, message: '请输入编码类型!'},
              { validator: (rule, value, callback) => validateDuplicateValue('mdm_code_rule', 'code_type', value, this.model.id, callback)},
           ],
           seqNo: [
              { required: true},
              { pattern: /^-?\d+$/, message: '请输入整数!'},
           ],
           seqLen: [
              { required: true},
              { pattern: /^-?\d+$/, message: '请输入整数!'},
           ],
        },
        url: {
          add: "/mdm/codeRule/add",
          edit: "/mdm/codeRule/edit",
          queryById: "/mdm/codeRule/queryById"
        }
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
        this.model = Object.assign({}, record);
        this.visible = true;
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
         
        })
      },
      dateFmt(date, fmt){
        var o = {
          "M+": date.getMonth() + 1,                   //月份
          "d+": date.getDate(),                        //日
          "h+": date.getHours(),                       //小时
          "m+": date.getMinutes(),                     //分
          "s+": date.getSeconds(),                     //秒
          "q+": Math.floor((date.getMonth() + 3) / 3), //季度
          "S": date.getMilliseconds()                  //毫秒
        };
        //  获取年份
        if (/(y+)/i.test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        }

        for (var k in o) {
          if (new RegExp("(" + k + ")", "i").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
          }
        }
        return fmt;
      }
    },
    watch: {
      model: {
        handler(newVal, oldVal){
          let prefix = this.model.prefix || '';
          let dateStr = '';
          if(String(this.model.dateFlag) === '1' && this.model.dateFmt){
            dateStr = this.dateFmt(new Date(), this.model.dateFmt);
          }
          let seqNo = '';
          let curSeqNo = String(this.model.seqNo) === '0' ? '1' : String(this.model.seqNo);
          let len = parseInt(this.model.seqLen);
          if(curSeqNo && len > 0){
            if(curSeqNo.length > len){
              seqNo = curSeqNo;
            }else{
              seqNo = (Array(len).join(0) + curSeqNo).slice(-len);
            }
          }
          this.model.codeExample = prefix + dateStr + seqNo
        },
        deep: true
      }
    }
  }
</script>